<?php
defined('ENV') || exit('illegal Access! @110');
/**
* 业务处理基类
* 连接数据库
* 获得分页信息
*/
class Model extends DB
{
    const table_name=''; //子类重写后, 调用时使用 static::table_name, 不能使用 self::table_name
    public $row = array();
    
	//分页函数
	public function setPage($num, $currentpage, $baseurl, $pagesize='')
	{
		$pagesize 		= empty($pagesize) ? 10 : $pagesize;			//每页显示多少条记录
		$totalpage 		= ceil($num / $pagesize);					//总共多少页
		$currentpage 	= empty($currentpage) ? 1 : $currentpage;		//当前页
		$lastpage 		= (($currentpage-1) <= 0)? 1: $currentpage-1;	//最后一页
		$nextpage 		= (($currentpage+1)>$totalpage) ? $totalpage : $currentpage+1;//下一页
		// $baseurl 	= empty($baseurl) ? $this->actionUrl : $baseurl;//不带分页的跳转链接
		$firstpageurl 	= $baseurl;
		$lastpageurl 	= $baseurl."/page/{$lastpage}";
		$nextpageurl 	= $baseurl."/page/{$nextpage}";
		$finalpageurl 	= $baseurl."/page/{$totalpage}";
		
		$pageinfo = array(
				'num'			=> $num,
				'currentpage' 	=> $currentpage,
				'totalpage' 	=> $totalpage,
				'firstpageurl' 	=> $firstpageurl,
				'lastpageurl' 	=> $lastpageurl,
				'nextpageurl' 	=> $nextpageurl,
				'finalpageurl' 	=> $finalpageurl);
		
		$start = ($currentpage - 1)*$pagesize;
		$limit = $start.','.$pagesize;
		return array(
			'page' => $pageinfo,
			'limit' => $limit
        );
	}
    /**
     * 获取链接
     * @return DB|null
     * @throws Exception
     */
    public static function getLink()
    {
        return self::link(static::table_name);
    }

    /**
     * 添加一条记录
     * @param array $arr 要添加的数据
     * @return int
     * @throws Exception
     */
    public static function addOne($arr)
    {
        return self::getLink()->insert($arr)->insertId;
    }

    public static function getGlobalId($project=1)
    {
        return self::link('gid')
            ->insert(['project' => $project])
            ->insertId;
    }

    /**
     * desc 符合条件的记录数, a=1, b=2 ... 等号判断
     * @param $table
     * @param $arr ['a' => 1, 'b' => 2]
     * @return bool|string
     * @throws Exception
     */
    public static function isExists($table, $arr)
    {
        $count = self::link($table)
            ->where($arr)
            ->count();
        
        return $count > 0 ? $count : FALSE;
    }

    /**
     * 获取unid对应的整数ID
     * @param $unid
     * @return mixed|string
     * @throws Exception
     */
    public static function getIdByUnid($unid)
    {
        $row = self::getOneByUnid($unid, 'id');
        return !empty($row['id']) ? $row['id'] : '';
    }
    
    /**
     * 通过主键id获取一行记录
     * @param string $id
     * @param string $fields
     * @return string
     */
    public static function getOneById($table, $id, $fields='*')
    {
        return self::getOneByFields([['id',$id]], $fields);
    }

    /**
     * 根据唯一id获取一条记录
     * @param $unid
     * @param string $fields
     * @return mixed|string
     * @throws Exception
     */
    public static function getOneByUnid($unid, $fields='*')
    {
        return self::getOneByFields([['unid', $unid]], $fields);
    }

    //获取一条记录
    public static function getOneByFields($arrWhere, $fields='*')
    {
        $table = static::table_name;
        $obj = self::link($table)->fields($fields)->limit(1);
        foreach ($arrWhere as $arr) {
            if (count($arr) == 2 && !is_array($arr[1])) {
                $obj->where([$arr[0] => $arr[1]]);
            } elseif (count($arr) == 2 && is_array($arr[1])) {
                $obj->whereIn($arr[0], $arr[1]);
            } elseif (count($arr) == 3) {
                $obj->whereOp($arr[0], $arr[1], $arr[2]);
            } else {
                $obj->addWhere('1=1');
            }
        }
        return  $obj->select()->getOne();
    }

    /**
     * 获取多条记录
     * @param array $arrWhere [[field, value], [field, [value1, value2, ..]], [field, '>', value]]
     * @param string $fields 要查询的字段
     * @param int $limit 条数
     * @param string $order 排序
     * @return mixed
     * @throws Exception
     */
    public static function getListByFields($arrWhere, $fields='*', $limit='', $order='')
    {
        $table = static::table_name;
        $obj = self::link($table)->fields($fields)->limit($limit)->order($order);
        foreach ($arrWhere as $arr) {
            if (count($arr) == 2 && !is_array($arr[1])) {
                $obj->where([$arr[0] => $arr[1]]);
            } elseif (count($arr) == 2 && is_array($arr[1])) {
                $obj->whereIn($arr[0], $arr[1]);
            } elseif (count($arr) == 3) {
                $obj->whereOp($arr[0], $arr[1], $arr[2]);
            } else {
                $obj->limit(1);
            }
        }
        return $obj->select()->getAll();
    }

    //保存一条数据, where id=xxx
    public static function saveById($arrData, $id)
    {
        return self::save($arrData, [['id', $id]]);
    }

    //保存一条数据, where unid=xxx
    public static function saveByUnid($arrData, $unid)
    {
        return self::save($arrData, [['unid', $unid]]);
    }

    //保存一条数据
    public static function save($arrData, $arrWhere)
    {
        $obj = self::link(static::table_name)->updateVal($arrData);

        foreach ($arrWhere as $arr) {
            if (count($arr) == 2 && !is_array($arr[1])) {
                $obj->where([$arr[0] => $arr[1]]);
            } elseif (count($arr) == 2 && is_array($arr[1])) {
                $obj->whereIn($arr[0], $arr[1]);
            } elseif (count($arr) == 3) {
                $obj->whereOp($arr[0], $arr[1], $arr[2]);
            }
        }

        return $obj->update()->affectRows;
    }
    
    //将join语句拆分成两次独立查询
    //利用到CRUD组装SQL时的数据
    public static function getJoinResult()
    {
    
    }
    
    //用来查询被分库分表的历史数据
    //用作数据查询的中间层, 自动判断是否要查到历史数据
    public static function getHistoryData()
    {
    
    }
    
}